<template>
  <div class="fillcontain">
    <head-top></head-top>
    <el-row style="margin-top: 20px;">
      <el-col :span="12" :offset="4">
        <el-form :model="formData" ref="formData" label-width="110px" class="demo-formData">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="任务要求" prop="requirement">
            <quillEditor v-model="formData.requirement" placeholder="请输入内容"></quillEditor>
          </el-form-item>
          <el-form-item :label="'所需设备' + index" label-width="100px" :key="index" v-for="(device, index) in formData.devices">

            <el-select v-model="device.selectIndex" filterable @change="handleSelect">
              <el-option
                v-for="item in menuOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
            <el-input v-model="device.count" placeholder="数量" style="width: 100px"></el-input>
            <el-button @click="delDevice(index)">删除设备</el-button>
          </el-form-item>

          <el-button @click="addDevice">新增设备</el-button>

          <el-form-item label="任务教程">
            <el-upload
              class="avatar-uploader"
              :action='uploadURL'
              :on-success="handleCourseSuccess"
              :file-list='formData.fileListC'
            >
              <i class="el-icon-plus"></i>  <!-- vue warning 是上传列表的问题  -->
              <div slot="tip" class="el-upload__tip">支持ppt、PDF、MD等格式</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="任务视频">
            <el-upload
              class="avatar-uploader"
              :action="uploadURL"
              :on-success="handleVideoSuccess"
              :file-list='formData.fileListV'
            >
              <i class="el-icon-plus"></i>  <!-- vue warning 是上传列表的问题  -->
              <div slot="tip" class="el-upload__tip">支持mp4等格式</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="连线图">
            <el-upload
              class="avatar-uploader"
              :action="uploadURL"
              :on-success="handleConnectSuccess"
              :file-list='formData.fileListCo'
            >
              <i class="el-icon-plus"></i>  <!-- vue warning 是上传列表的问题  -->
              <div slot="tip" class="el-upload__tip">支持ppt、PDF等格式</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="任务仿真">
            <el-upload
              class="avatar-uploader"
              :action="uploadURL"
              :on-success="handleSimSuccess"
              :file-list='formData.fileListS'
            >
              <i class="el-icon-plus"></i>  <!-- vue warning 是上传列表的问题  -->
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
          </el-form-item>

          <el-form-item label="仿真步骤描述" prop="SDescription">
            <quillEditor v-model="formData.SDescription" placeholder="请输入内容"> </quillEditor>
          </el-form-item>

          <el-form-item :label="'仿真验证点' + index" label-width="100px" :key="index" v-for="(device, index) in formData.CkFormData"> <!---选项限制为上面选取的设备-->
            <el-input v-model="device.name" placeholder="验证点描述"></el-input>
            <el-select v-model="device.selectIndex" filterable>
              <el-option
                v-for="item in CkChoice"
                :key="item.label"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
            <el-transfer v-model="device.selectIndexList" :data="CkChoice" @change="handleChange" :titles="['可用设备', '已选设备']"> </el-transfer>
            <!--<el-select v-model="device.selectIndexList" filterable  @change="handleSelect" multiple> &lt;!&ndash;-可以change的时候删除可选列表-&ndash;&gt;-->
              <!--{{CkChoice}}-->
              <!--<el-option-->
                <!--v-for="item in CkChoice"-->
                <!--:key="item.selectIndex"-->
                <!--:label="item.selectIndex"-->
                <!--:value="item.selectIndex">   可能也是list不会刷新的问题-->
                <!--{{item}}-->
              <!--</el-option>-->
            <!--</el-select>-->
            <el-button @click="delCkDevice(index)">删除设备</el-button>
          </el-form-item>
          <el-button @click="addCkDevice">新增验证点</el-button>
          <el-form-item label="案例插件">
            <el-upload
              class="avatar-uploader"
              :action="uploadURL"
              :on-success="handleRealSuccess"
              :file-list='formData.fileListR'
            >
              <i class="el-icon-plus"></i>  <!-- vue warning 是上传列表的问题  -->
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
          </el-form-item>

          <el-form-item label="案例步骤描述" prop="PDescription">
            <quill-editor v-model="formData.PDescription" placeholder="请输入内容"> </quill-editor>
          </el-form-item>

          <el-form-item label="实验报告模版" prop="PDescription">
            <quill-editor v-model="formData.reportTemp" placeholder="请输入内容"> </quill-editor>
          </el-form-item>

          <el-form-item class="button_submit">
            <el-button type="primary" @click="createTask(1)" v-if="taskId">更新</el-button>
            <el-button type="primary" @click="createTask(0)" v-else>立即创建</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import headTop from './head.vue'
  import {DeviceName, createTask, updateTask, getTaskData, uploadURL} from '@/api/api'
  import { quillEditor } from 'vue-quill-editor'
  export default {
    created () {
      this.getMenu()
    },
    watch: {  // 加了这个才能传递参数
      '$route': 'getMenu'
    },
    computed: {
      CkChoice: function () {
        const data = []
        this.formData.devices.forEach((item, index) => {
          [...Array(parseInt(item.count)).keys()].forEach((index) => {
            data.push({
              key: item.selectIndex + index,
              label: item.selectIndex + index
            })
          })
        })
        return data
      }
    },
    data () {
      return {
        uploadURL: uploadURL,
        formData: {
          name: '',
          devices: [{
            selectIndex: '',
            count: '1'
          }],
          CkFormData: [{
            name: '',
            step: 0,  // 暂时不懂什么用，忘记了
            selectIndex: '',
            selectIndexList: []
          }],
          courseUrl: '',
          videoUrl: '',
          connectUrl: '',
          fileListC: [],
          fileListV: [],
          fileListCo: [],
          fileListS: [],
          fileListR: [],
          simUrl: '',
          realUrl: '',
          requirement: '123',
          PDescription: '44444',
          SDescription: '789',
          reportTemp: '22'
        },
        taskId: '',
        menuOptions: [],
        fileList: []
      }
    },
    components: {
      headTop,
      quillEditor
    },
    methods: {
      async getMenu () {
        this.menuOptions = []
        try {
          DeviceName().then((res) => {
            res.data.forEach((item, index) => {
              this.menuOptions.push({
                label: item.name,
                value: item.id,
                index
              })
            })
          })
        } catch (err) {
          console.log('获取设备名称失败', err)
        }
        this.formData.devices = [{
          selectIndex: '',
          count: '1'
        }]
        this.formData.CkFormData = [{
          name: '',
          step: 0,
          selectIndex: '',
          selectIndexList: []
        }]
        this.formData.name = ''
        this.formData.courseUrl = ''
        this.formData.videoUrl = ''
        this.formData.connectUrl = ''
        this.formData.simUrl = ''
        this.formData.realUrl = ''
        this.formData.requirement = ''
        this.formData.PDescription = ''
        this.formData.SDescription = ''
        this.formData.reportTemp = ''
        this.formData.fileListC = []
        this.formData.fileListV = []
        this.formData.fileListS = []
        this.formData.fileListR = []
        this.taskId = this.$route.params.taskId
        if (this.taskId) {
          try {
            getTaskData(this.taskId).then((res) => {  // TODO: 验证点设备待处理
              let task = res.data.task
              let deviceList = task.deviceList
              let cpList = res.data.cpList
              this.formData.name = task.name
              this.formData.courseUrl = task.course
              this.formData.videoUrl = task.video
              this.formData.connectUrl = task.connectPhoto
              this.formData.simUrl = task.simulation
              this.formData.realUrl = task.real
              this.formData.requirement = task.requirement
              this.formData.PDescription = task.PDescription
              this.formData.SDescription = task.SDescription
              this.formData.reportTemp = task.reportTemp
              this.formData.fileListC = task.course?[{
                name: task.name,
                url: task.course,
                status: 'finished'
              }]:[]
              this.formData.fileListV = task.course?[{
                name: task.name,
                url: task.video,
                status: 'finished'
              }]:[]
              this.formData.fileListCo = task.course?[{
                name: task.name,
                url: task.connectPhoto,
                status: 'finished'
              }]:[]
              this.formData.fileListS = task.course?[{
                name: task.name,
                url: task.simulation,
                status: 'finished'
              }]:[]
              this.formData.fileListR = task.course?[{
                name: task.name,
                url: task.real,
                status: 'finished'
              }]:[]
              // 设备列表
              let that = this
              that.formData.devices = []
              deviceList.forEach( device => {
                that.formData.devices.push({
                  selectIndex: device.DeviceName_name,
                  count: device.count
                })
              })
              // 验证点
              that.formData.CkFormData = []
              cpList.forEach( cp => {
                that.formData.CkFormData.push({
                  name: cp.name,
                  selectIndex: cp.main,
                  selectIndexList: cp.connect
                })
              })
            })
          } catch (err) {
            console.log('获取设备名称失败', err)
          }
        }
      },
      handleSelect (index) {
        this.selectIndex = index
        this.selectMenu = this.menuOptions[index]
      },
      addDevice () {
        this.formData.devices.push({
          selectIndex: '',
          count: '1'
        })
      },
      delDevice (index) {
        this.formData.devices.splice(index, 1)
      },
      addCkDevice () {
//        let list = this.formData.CkFormData
//        let step = list[list.length - 1].step + 1
        this.formData.CkFormData.push({
          name: '',
          selectIndex: '',
          selectIndexList: []
//          step: step
        })
      },
      delCkDevice (index) {
        this.formData.CkFormData.splice(index, 1)
      },
      handleChange (value, direction, movedKeys) {  // TODO：刷新数组，不然框架监控不到数据改变,好像没有用
        this.formData.CkFormData.push({})
        this.formData.CkFormData.splice(-1, 1)
      },
      handleCourseSuccess (res, file) {
//        this.imageUrl = URL.createObjectURL(file.raw)
        this.formData.courseUrl = res.name
      },
      handleVideoSuccess (res, file) {
//        this.imageUrl = URL.createObjectURL(file.raw)
        this.formData.videoUrl = res.name
      },
      handleConnectSuccess (res, file) {
//        this.imageUrl = URL.createObjectURL(file.raw)
        this.formData.connectUrl = res.name
      },
      handleSimSuccess (res, file) {
//        this.imageUrl = URL.createObjectURL(file.raw)
        this.formData.simUrl = res.name
      },
      handleRealSuccess (res, file) {
//        this.imageUrl = URL.createObjectURL(file.raw)
        this.formData.realUrl = res.name
      },
      async createTask (update) {
//        let checkpoint = {
//          rootDev: this.formData.CkFormData.devices.selectIndex,
//          leafDev: this.formData.CkFormData.devices.selectIndexList
//        }
        let postData = {
          name: this.formData.name,
          course: this.formData.courseUrl,
          video: this.formData.videoUrl,
          connectPhoto: this.formData.connectUrl,
          simulation: this.formData.simUrl,
          real: this.formData.realUrl,
          learnTime: 45,
          totalTime: 45,
          requirement: this.formData.requirement,
          SDescription: this.formData.SDescription,
          PDescription: this.formData.PDescription,
          reportTemp: this.formData.reportTemp,
          TDeviceList: this.formData.devices,
//          checkpoint: checkpoint
          checkpoint: this.formData.CkFormData
        }
        if (update) {
          updateTask(this.taskId, postData).then(res => {
            if (res.status === 200) {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
              this.$router.push({path: '/manage/taskList'})  // FIXME: 不会刷新
            } else {
              this.$message({
                type: 'error',
                message: '添加失败'
              })
            }
          })
        } else {
          createTask(postData).then(res => {
            if (res.status === 200) {
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.$router.push({path: '/manage/taskList'})  // FIXME: 不会刷新
            } else {
              this.$message({
                type: 'error',
                message: '添加失败'
              })
            }
          }).catch(error => {
            this.$message({
              type: 'error',
              message: '添加失败'
            })
            console.log('类型添加失败', error)
          })
        }
      }
//      updatefileList (res, file, fileList) {
//        debugger
//        res
//        file
//      }
    }
  }
</script>

